﻿using System;
using System.Diagnostics;
using System.Net;
using System.Windows;
using System.Windows.Media;
using System.Windows.Navigation;
using AgiliTrain.PhoneyTools.SystemResources;
using GooNews.ViewModels;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using System.Text;
using System.IO;
using System.IO.IsolatedStorage;

namespace GooNews.Pages
{
  /// <summary>
  /// 
  /// </summary>
  public partial class ShowSummaryPage
  {
    FeedItem _currentStory = null;
    bool _isInitialBrowseComplete = false;
    Uri _initialUri;

    /// <summary>
    /// Initializes a new instance of the <see cref="ShowSummaryPage"/> class.
    /// </summary>
    public ShowSummaryPage()
    {
      InitializeComponent();

      Loaded += new RoutedEventHandler(ShowSummaryPage_Loaded);
      browser.Navigated += new EventHandler<NavigationEventArgs>(browser_Navigated);

      ieButton = (ApplicationBarMenuItem)ApplicationBar.MenuItems[0];
      shareViaEmailButton = (ApplicationBarMenuItem)ApplicationBar.MenuItems[1];
      instaPaperButton = (ApplicationBarMenuItem)ApplicationBar.MenuItems[2];
      instaPaperButton.IsEnabled = App.ViewModel.Options.AllowInstaPaper;

#if MANGO
      urlBarButton = ApplicationBar.Buttons[1] as ApplicationBarIconButton;
      urlBarButton.IsEnabled = false;

      urlTextBox.MouseLeftButtonUp += (s, e) =>
        {
          urlTextBox.IsReadOnly = true;
        };
#endif
    }

    /// <summary>
    /// Handles the Navigated event of the browser control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.Navigation.NavigationEventArgs"/> instance containing the event data.</param>
    void browser_Navigated(object sender, NavigationEventArgs e)
    {
      if (!_isInitialBrowseComplete)
      {
        _isInitialBrowseComplete = true;
        _initialUri = e.Uri;
        busyPane.Visibility = Visibility.Collapsed;
        ApplicationBar.IsVisible = true;
        App.ViewModel.ShowMemoryConsuption();
      }
      ieButton.IsEnabled = e.Uri != null;
      shareViaEmailButton.IsEnabled = e.Uri != null;
      instaPaperButton.IsEnabled = e.Uri != null && App.ViewModel.Options.AllowInstaPaper;
#if MANGO
      urlBarButton.IsEnabled = e.Uri != null;
      urlTextBox.Text = e.Uri == null ? "" : e.Uri.ToString();
      urlTextBox.SelectAll();
      urlTextBox.IsEnabled = urlTextBox.Text.Length > 0;
#endif
    }

    /// <summary>
    /// Handles the Loaded event of the ShowSummaryPage control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    void ShowSummaryPage_Loaded(object sender, RoutedEventArgs e)
    {
      ShowCurrentStory();
      if (_currentStory != null)
      {
        busyPane.Visibility = System.Windows.Visibility.Visible;
        ApplicationBar.IsVisible = false;
        var story = BuildInitialPage(_currentStory.Summary);

        // HACK to get around problem with 
        const string path = "/summarypage.html";
        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
        {
          if (store.FileExists(path)) store.DeleteFile(path);
          var file = store.CreateFile(path);
          var writer = new StreamWriter(file);
          writer.Write(story);
          writer.Flush();
          writer.Close();
        }
        browser.Navigate(new Uri(path, UriKind.Relative));
      }
    }

    private string BuildInitialPage(string body)
    {
      string frame = @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN"" ""http://www.w3.org/TR/html4/strict.dtd"">
<html>
<head>
  <meta HTTP-EQUIV=""content-type"" CONTENT=""text/html; charset=utf-8"">
  <meta name=""viewport"" content=""width={1}"">
  <style type=""text/css"">
    {2}
  </style>
</head>
<body>
  {0}
</body>
</html>";
      var results = string.Format(frame, body,
        browser.ActualWidth - (App.ThisApp.RootFrame.Orientation == PageOrientation.Portrait ? 24 : 96),
        GetStoryCSS());

      return FixFonts(results);
    }

    private string FixFonts(string results)
    {
      return results.Replace("font-family:arial", "font-family:Segoe WP,arial");
    }

    private object GetStoryCSS()
    {
      var styles = @"body
{{
background-color: {0};
color: {1};
}}
a:link {{color:{2};}} 
a:visited {{color:{2};}}
a:hover {{color:{2};}} 
a:active {{color:{2};}}
img {{border: 0;}}
.p {{ margin-top: 5px; }}
";

      return string.Format(styles,
        CreateWebColor(PhoneColors.PhoneBackgroundColor),
        CreateWebColor(PhoneColors.PhoneForegroundColor),
        CreateWebColor(PhoneColors.PhoneAccentColor));
    }

    private string CreateWebColor(Color color)
    {
      return string.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
    }

    /// <summary>
    /// Fixes the URI.
    /// </summary>
    /// <param name="uri">The URI.</param>
    /// <returns></returns>
    private string FixUri(Uri uri)
    {
      var query = uri.Query.Replace("/", HttpUtility.UrlEncode("/")); ;
      var rest = uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped);

      return string.Concat(rest, query);

    }

    /// <summary>
    /// Called just before a page is no longer the active page in a frame.
    /// </summary>
    /// <param name="e">An object that contains the event data.</param>
    protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
    {
      base.OnNavigatingFrom(e);

      Debug.WriteLine("Leaving Summary");

      // Try and clean up the crud
      browser.Visibility = Visibility.Collapsed;
      browser.IsScriptEnabled = false;
    }

    /// <summary>
    /// Called when a page becomes the active page in a frame.
    /// </summary>
    /// <param name="e">An object that contains the event data.</param>
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
      base.OnNavigatedTo(e);

      // Reverse the Cleanup
      browser.Visibility = Visibility.Visible;
      browser.IsScriptEnabled = true;

      // Grab the story from the query string
      ShowCurrentStory();

    }

    /// <summary>
    /// Shows the current story.
    /// </summary>
    void ShowCurrentStory()
    {
      if (_currentStory == null)
      {
        try
        {

          int feedIndex = int.Parse(NavigationContext.QueryString["feed"]);
          int storyIndex = int.Parse(NavigationContext.QueryString["story"]);
          _currentStory = App.ViewModel.Feeds[feedIndex].FeedItems[storyIndex];
        }
        catch
        {
          if (NavigationService.CanGoBack &&
            !App.ViewModel.IsLocked)
          {
            NavigationService.GoBack();
          }
        }
      }

      DataContext = _currentStory;

    }

    /// <summary>
    /// Handles the Click event of the ieButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private void ieButton_Click(object sender, EventArgs e)
    {
      App.DoHaptic();
      WebBrowserTask task = new WebBrowserTask();
      task.URL = browser.Source.AbsoluteUri;
      task.Show();
    }

    /// <summary>
    /// Handles the Click event of the instaPaperButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private void instaPaperButton_Click(object sender, EventArgs e)
    {
      App.DoHaptic();
      busyPane.Visibility = Visibility.Visible;
      ApplicationBar.IsVisible = false;

      _currentStory.SendToInstaPaper(browser.Source.AbsoluteUri, (r) =>
        {
          busyPane.Visibility = Visibility.Collapsed;
          ApplicationBar.IsVisible = true;
          if (r)
          {
            App.ThisApp.ShowMessage("Added to InstaPaper");
          }
        });
    }

    /// <summary>
    /// Handles the Click event of the shareViaEmailButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private void shareViaEmailButton_Click(object sender, EventArgs e)
    {
      App.DoHaptic();
      _currentStory.SendToEmail(browser.Source.AbsoluteUri);
    }

    /// <summary>
    /// Handles the Click event of the refreshButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    private void refreshButton_Click(object sender, EventArgs e)
    {
      try
      {
        browser.InvokeScript("eval", "history.go()");
      }
      catch
      {
        // Eat error
      }
    }

#if MANGO
    bool _isUrlBarShown = false;
    private void urlBarButton_Click(object sender, EventArgs e)
    {
      if (_isUrlBarShown)
      {
        VisualStateManager.GoToState(this, "Hidden", true);
      }
      else
      {
        VisualStateManager.GoToState(this, "Shown", true);
      }
      _isUrlBarShown = !_isUrlBarShown;
    }
#endif


  }
}